import { resetRouter } from '@/router'
import { getInfo, getMoreInfo, login } from '../../api/user'
import { getToken, removeToken, setToken } from '../../utils/auth'
const state = () => ({
  token: getToken(),
  userInfo: {}
})

const mutations = {
  // 方法 插件里能检测到数据同步更新
  setToken(state, newToken) {
    state.token = newToken
  },

  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    // 用cookies保存
    setToken(res)
    // vuex保存
    context.commit('setToken', res)
  },

  async getUserInfo(context) {
    const res = await getInfo()
    const moreres = await getMoreInfo({ id: res.userId })
    context.commit('setUserInfo', { ...res, ...moreres })
  },

  logout(context) {
    removeToken()
    context.commit('setToken', '')
    context.commit('setUserInfo', {})
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
